<template>
  <div class="page-common-layout">
    <div class="page-common-content">
      <tool-bar
        @search="$refs.masterList.onOrganizationSearch(parameter.orgName)"
        @reset="handleReset()"
      >
        <template slot="toolBtn" slot-scope="scope">
          <a-dropdown v-action:organizationAddDialog>
            <a-menu slot="overlay">
              <a-menu-item
                v-for="item in groupButtons"
                :key="item.uuid"
                @click="
                  (e) => {
                    handleAdd(item, $refs.masterList.data);
                  }
                "
              >
                <a-icon type="plus" />
                新建{{ item.dicItemName }}
              </a-menu-item>
            </a-menu>
            <a-button class="cu-btn-primary" icon="plus">
              新建
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
          <!--          <import-data icon="upload" type="link">导入</import-data>-->

          <!-- <export-data
            fileName="组织机构"
            fieldInfoUrl="/mdata/organization/getFieldInfo"
            exportUrl="/mdata/organization/exportOrganizationData"
          ></export-data> -->

          <!-- <a-button icon="download" type="link">导出</a-button> -->
          <!-- <a-button icon="search" @click="viewOrg">查看组织机构</a-button> -->

          <a-icon
            type="setting"
            @click="columnSortVisible = true"
            style="float: right; margin: 9px 5px 0 0;"
          />
        </template>
        <template slot="toolForm">
          <a-form-item label="">
            <a-input
              v-model="parameter.orgName"
              placeholder="名称"
              style="width:350px"
            />
          </a-form-item>
          <!-- <a-form-item label="编码">
            <a-input v-model="parameter.orgCode" placeholder="编码" />
          </a-form-item> -->
        </template>
      </tool-bar>

      <TreeGrid
        ref="masterList"
        :columns="masterColumns"
        :url="url"
        rowKey="uuid"
        :loadAll="true"
        :parameter="parameter"
        :showRowSelect="false"
        :pagination="false"
        @rowClick="masterRowClick"
        :defaultExpandAllRows="false"
        :expand="false"
      >
        <span slot="edit" slot-scope="{ record }">
          <template>
            <a
              @click="handleEdit(record, $refs.masterList.data)"
              v-if="record.isSystem == 0"
              v-action:organizationEditDialog
            >
              编辑
            </a>
          </template>
        </span>
        <span slot="renderAction" slot-scope="{ record }">
          <template>
            <a
              @click="handleDelClick(record)"
              class="action-delete"
              v-if="record.isSystem == 0"
              v-action:organizationDelDialog
            >
              删除
            </a>
            <span class="action-margin"></span>
            <a @click="previewUser(record)">查看用户</a>
          </template>
        </span>
      </TreeGrid>
      <!--部门新增编辑-->
      <departForm
        ref="departModal"
        :visible="departVisible"
        :loading="masterConfirmLoading"
        :model="departMdl"
        @cancel="handleDepartCancel"
        @ok="handleOk('departModal')"
      />
    </div>

    <!--    	公司新增编辑-->
    <transition
      enter-active-class="animated lightSpeedInLeft faster"
      leave-active-class="animated bounceOutLeft fast"
    >
      <companyForm
        ref="companyModal"
        :visible="companyVisible"
        :loading="masterConfirmLoading"
        :model="companyMdl"
        @cancel="handleCancel()"
        @ok="handleOk('companyModal')"
      />
    </transition>

    <!-- 项目新增编辑 -->
    <peojectForm
      ref="projectModal"
      :visible.sync="projectVisible"
      :model="projectMdl"
      :key="projectKey"
    ></peojectForm>

    <!-- 标段新增编辑 -->
    <blockForm
      ref="blockModal"
      :visible.sync="blockVisible"
      :model="blockMdl"
      :key="blockKey"
    ></blockForm>

    <user-view
      ref="userViewModal"
      v-if="userViewVisible"
      :visible="userViewVisible"
      :orgId="orgId"
      :orgName="orgName"
      @close="userViewVisible = false"
    >
    </user-view>

    <org-preview
      ref="viewOrgModal"
      :visible="viewOrgVisible"
      @cancel="viewOrgVisible = false"
    >
    </org-preview>

    <column-sort
      :visible="columnSortVisible"
      :columns="masterColumns"
      @ok="columnSortVisible = false"
      @cancel="columnSortVisible = false"
    >
    </column-sort>
  </div>
</template>

<script>
import { TreeGrid, ExportData, ImportData } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import departForm from "./departEdit";
import companyForm from "./companyEdit";
// import peojectForm from "./peojectEdit";
// import blockForm from "./blockEdit";
import peojectForm from "../projectData/peojectEdit.vue";
import blockForm from "../projectData/blockEdit.vue";
import userView from "./userView";
import orgPreview from "@/components/TopVUI/custom/orgPreview.vue";
import { getTreeProject } from "@/services/user.js";
export default {
  name: "Table",
  components: {
    TreeGrid,
    departForm,
    companyForm,
    userView,
    orgPreview,
    ExportData,
    ImportData,
    peojectForm,
    blockForm,
  },
  mixins: [treeGridMixin],
  data() {
    return {
      masterColumns: [
        {
          title: "名称",
          align: "left",
          dataIndex: "orgName",
          langCode: "name",
          width: 300,
        },
        {
          title: "类型",
          dataIndex: "orgTypeDesc",
          width: 80,
          //   scopedSlots: { customRender: "renderOrgType" },
        },
        {
          title: "操作",
          width: 100,
          align: "center",
          dataIndex: "editAction",
          scopedSlots: { customRender: "edit" },
        },
        {
          title: "排序",
          dataIndex: "orgSort",
          width: 80,
        },

        {
          title: "创建时间",
          dataIndex: "createTime",
          width: 80,
        },
        {
          title: "操作",
          width: 100,
          align: "center",
          dataIndex: "action",
          scopedSlots: { customRender: "renderAction" },
        },
      ],
      companyVisible: false,
      departVisible: false,
      masterConfirmLoading: false,
      companyMdl: null,
      departMdl: null,
      // 查询参数
      masterQueryParam: {},
      url: {
        fathersUrl: "/mdata/organization/getTreeSysOrganizationByOrg",
        // fathersUrl: "/mdata/organization/getListByPid",// 企业微信导入组织机构没有层级不能用上面的
        expandUrl: "/mdata/organization/getListByPid",
        masterUpdate: "/mdata/organization/update",
        masterDelete: "/mdata/organization/delete",
        masterSave: "/mdata/organization/save",
        getListByKeywords: "/mdata/user/getListByKeywords",
        getDicItemByCode: "/system/dicSet/getDicItemByCode",
      },
      parameter: {},
      key: "1",
      userViewVisible: false,
      viewOrgVisible: false,
      orgId: "",
      orgName: "",
      columnSortVisible: false,
      //
      groupButtons: [],
      projectKey: "asdfghj",
      projectVisible: false,
      projectMdl: {},
      blockKey: "zxcvbnm",
      blockVisible: false,
      blockMdl: {},
      //
      currentDictCode: "",
    };
  },
  filters: {},
  mounted() {
    this.getAddTypeList();
  },

  methods: {
    handleReset() {
      this.parameter.orgName = "";
      this.$refs.masterList.onOrganizationSearch(this.parameter.orgName);
    },
    //查询列表数据
    getTableData() {
      this.$refs.masterList.refresh(true);
    },

    //删除
    async handleDelClick(record) {
      let valid = await this.handleSub(record);
      valid && this.getTreeProjectData();
    },

    getUpdate() {
      this.$refs.masterList.refresh();
    },

    //查询新增类型
    getAddTypeList() {
      this.$post("/system/dicSet/getDicItemByCode", {
        code: "OrganizationsType",
      })
        .then((res) => {
          let { data } = res;
          this.groupButtons = data ?? [];
          //   let code = ["org_type.01", "org_type.02", "org_type.07"];
          //   this.groupButtons = this.groupButtons.filter((v) =>
          //     code.includes(v.dicItemCode)
          //   );
        })
        .catch((_) => {
          this.groupButtons = [];
        })
        .finally((_) => {});
    },

    viewOrg() {
      this.viewOrgVisible = true;
      this.$refs.viewOrgModal.getOrgData(this.$refs.masterList.data);
    },

    handleCancel: function() {
      this.companyVisible = false;
    },

    // 新增
    handleAdd: function(key, treeData, e) {
      let { dicItemCode, dicItemName } = key;
      this.currentDictCode = dicItemCode;
      let form = {};
      this.companyMdl = null;
      this.departMdl = null;
      //公司
      if (dicItemCode == "org_type.01" || dicItemCode == "org_type.07") {
        //清理表单数据
        form = this.$refs.companyModal.form;
        form.resetFields();
        this.companyVisible = true;
        this.$refs.companyModal.title = "新建" + dicItemName;
      }
      //部门
      else if (dicItemCode == "org_type.02") {
        // 清理表单数据
        form = this.$refs.departModal.form;
        form.resetFields();
        this.departVisible = true;
        this.$refs.departModal.title = "新建" + dicItemName;
      }
      //项目
      else if (dicItemCode == "org_type.04") {
        this.projectKey = Date.now();
        this.projectVisible = true;
        this.projectMdl = {
          text: "新建" + dicItemName,
        };
      }
      //标段
      else if (dicItemCode == "org_type.05") {
        this.blockKey = Date.now();
        this.blockVisible = true;
        this.blockMdl = {
          text: "新建" + dicItemName,
        };
      }
    },

    // 编辑
    handleEdit: function(record, data) {
      this.currentDictCode = record.orgType;
      this.$post("/mdata/organization/getDetailByUuid", {
        uuid: record.uuid,
      }).then((res) => {
        if (res.statusCode === 200) {
          if (
            record.orgType == "org_type.01" ||
            record.orgType == "org_type.07"
          ) {
            this.$refs.companyModal.title = "编辑";
            this.companyMdl = res.data;
            this.companyVisible = true;
          } else if (record.orgType == "org_type.02") {
            this.$refs.departModal.title = "编辑";
            this.departMdl = res.data;
            this.departVisible = true;
          } else if (record.orgType == "org_type.04") {
            this.projectMdl = {
              text: "编辑",
              ...res.data,
            };
            this.projectVisible = true;
          } else if (record.orgType == "org_type.05") {
            this.blockMdl = {
              text: "编辑",
              ...res.data,
            };
            this.blockVisible = true;
          }
        }
      });
    },

    //查询全局项目集合
    getTreeProjectData() {
      return new Promise((resolve, reject) => {
        getTreeProject()
          .then((res) => {
            let source = res.data || [];
            this.$store.dispatch("setStoreState", {
              TENANT_DATA: source,
            });
            resolve();
          })
          .catch((_) => {
            this.$store.dispatch("setStoreState", {
              TENANT_DATA: [],
            });
            reject();
          });
      });
    },

    // 提交表单
    handleOk: function(e) {
      let url = "";
      let form = {};
      if (e === "departModal") {
        form = this.$refs.departModal.form;
      } else if (e === "companyModal") {
        form = this.$refs.companyModal.form;
      } else if (e === "projectModal") {
        form = this.$refs.projectModal.form;
      }
      form.validateFields((errors, values) => {
        if (!errors) {
          if (e === "companyModal") {
            this.masterConfirmLoading = true;
            values.orgType = this.currentDictCode;
            if (!values.uuid) {
              url = this.url.masterSave;
            } else {
              url = this.url.masterUpdate;
            }
          } else {
            values.orgType = "org_type.02";
            if (!values.uuid) {
              url = this.url.masterSave;
            } else {
              url = this.url.masterUpdate;
            }
          }
          this.$post(url, values)
            .then((res) => {
              if (res === 1 || res.statusCode === 200) {
                if (e === "companyModal") {
                  this.companyVisible = false;
                } else {
                  this.departVisible = false;
                }
                this.getTreeProjectData();
                this.$refs.masterList.refresh();
                this.$message.success(
                  res.message ? res.message : "操作成功",
                  1.5
                );
              } else {
                this.$message.error(
                  res.message ? res.message : "操作失败",
                  1.5
                );
              }
            })
            .finally(() => {
              this.masterConfirmLoading = false;
            });
        }
      });
    },
    // 取消
    handleCompanyCancel(type) {
      this.companyMdl = null;
      this.companyVisible = false;
    },
    handleDepartCancel(type) {
      this.departMdl = null;
      this.departVisible = false;
    },

    previewUser(record) {
      this.userViewVisible = true;
      this.orgId = record.id;
      this.orgName = "查看用户-【" + record.orgName + "】";
    },
  },
};
</script>

<style scoped lang="less">
.table {
  background-color: @base-bg-color;
  padding: 24px;
}
</style>
